import { useState } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';
import { Button } from '@/components/ui/Button';
import { Input } from '@/components/ui/Input';
import { Textarea } from '@/components/ui/Textarea';
import { useStore } from '@/lib/hooks/useStore';
import { fileToBase64 } from '@/lib/utils';
import { v4 as uuidv4 } from 'uuid';

// 验证架构
const checkInSchema = z.object({
  note: z.string().optional(),
  date: z.string().refine(val => !isNaN(Date.parse(val)), {
    message: '请输入有效的日期',
  }),
});

type CheckInFormData = z.infer<typeof checkInSchema>;

interface CheckInFormProps {
  planId: string;
  onSuccess?: () => void;
}

export function CheckInForm({ planId, onSuccess }: CheckInFormProps) {
  const { addCheckIn, setPlayCongratulationSound } = useStore();
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [imageFile, setImageFile] = useState<File | null>(null);
  const [previewUrl, setPreviewUrl] = useState<string | null>(null);

  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
  } = useForm<CheckInFormData>({
    resolver: zodResolver(checkInSchema),
    defaultValues: {
      note: '',
      date: new Date().toISOString().substring(0, 16),
    },
  });

  const handleImageChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0] || null;
    if (file) {
      setImageFile(file);
      const url = URL.createObjectURL(file);
      setPreviewUrl(url);
    }
  };

  const onSubmit = async (data: CheckInFormData) => {
    setIsSubmitting(true);
    
    try {
      let imageUrl = '';
      
      if (imageFile) {
        // 转换图片为base64字符串
        imageUrl = await fileToBase64(imageFile);
      }
      
      const checkInData = {
        id: uuidv4(),
        date: new Date(data.date),
        note: data.note,
        imageUrl: imageUrl || undefined,
        planId,
      };
      
      addCheckIn(checkInData);
      
      // 播放恭喜音效
      setPlayCongratulationSound(true);
      
      reset();
      setImageFile(null);
      setPreviewUrl(null);
      onSuccess?.();
    } catch (error) {
      console.error('打卡失败', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
      <div>
        <label htmlFor="date" className="block text-sm font-medium text-gray-700 mb-1">
          打卡日期 <span className="text-red-500">*</span>
        </label>
        <Input
          id="date"
          type="datetime-local"
          {...register('date')}
          error={!!errors.date}
        />
        {errors.date && (
          <p className="mt-1 text-sm text-red-500">{errors.date.message}</p>
        )}
      </div>

      <div>
        <label htmlFor="note" className="block text-sm font-medium text-gray-700 mb-1">
          打卡备注
        </label>
        <Textarea
          id="note"
          placeholder="记录一下今天的完成情况"
          {...register('note')}
        />
      </div>

      <div>
        <label htmlFor="image" className="block text-sm font-medium text-gray-700 mb-1">
          上传图片
        </label>
        <Input
          id="image"
          type="file"
          accept="image/*"
          onChange={handleImageChange}
          className="py-1"
        />
        
        {previewUrl && (
          <div className="mt-2">
            <img
              src={previewUrl}
              alt="预览"
              className="h-40 w-auto object-cover rounded-md"
            />
          </div>
        )}
      </div>

      <div className="flex justify-end space-x-2 pt-2">
        <Button
          type="button"
          variant="outline"
          onClick={() => {
            reset();
            setImageFile(null);
            setPreviewUrl(null);
            onSuccess?.();
          }}
        >
          取消
        </Button>
        <Button type="submit" variant="primary" disabled={isSubmitting}>
          {isSubmitting ? '提交中...' : '提交打卡'}
        </Button>
      </div>
    </form>
  );
} 